#include"Util.h"

//判断文件是否存在
bool aod::FileUtil::Exist()
{
    int ret = access(_name.c_str(),F_OK);
    if(ret)
    {
        return false;
    }
    return true;
}
//获取文件大小
size_t aod::FileUtil::Size()
{
    if(this->Exist() == false)
    {
        return 0;
    }
    struct stat st;
    int ret = stat(_name.c_str(),&st);
    if(ret != 0)
    {
        return 0;
    }       
    return st.st_size;

}

//获取文件数据到body中
bool aod::FileUtil::GetContent(std::string* body)
{
    std::ifstream ifs;
    ifs.open(_name,std::ios::binary);
    if(ifs.is_open() == false)
    {
        std::cout << "open file failed!\n" << std::endl;
        return false;
    }
    size_t len = this->Size();
    body->resize(len);
    ifs.read(&(*body)[0],len);
    if(ifs.good() == false)
    {
        std::cout << "read file failed!\n" << std::endl;
        ifs.close();
        return false;
    }
    ifs.close(); 
    return true;
}

//向文件写入数据
bool aod::FileUtil::SetContent(const std::string& body)
{
    std::ofstream ofs;
    ofs.open(_name,std::ios::binary);
    if(ofs.is_open() == false)
    {
        std::cout << "open file failed!\n" << std::endl;
        return false;
    }
    
    ofs.write(body.c_str(),body.size());
    if(ofs.good() == false)
    {
        std::cout << "write file failed!\n" << std::endl;
        ofs.close();
        return false;
    }
    ofs.close(); 
    return true;
}

//针对目录时创建目录
bool aod::FileUtil::CreateDirectory()
{
    if(this->Exist())
    {
        std::cout << "Directory already exists: " << _name << std::endl;
        return true;
    }
    std::cout << "Creating directory: " << _name << std::endl;
    return mkdir(_name.c_str(), 0777) == 0;
}

bool aod::JsonUtil::Serialize(const Json::Value &Value,std::string* body)
{
    Json::StreamWriterBuilder swb;
    std::unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());


    std::stringstream ss;
    int ret = sw->write(Value,&ss);
    if(ret != 0)
    {
        std::cout << "Serialize failed!\n";
        return false; 
    }
    *body = ss.str();
    return true;
}

bool aod::JsonUtil::UnSerialize(const std::string& body,Json::Value* Value)
{
    Json::CharReaderBuilder crb;
    std::unique_ptr<Json::CharReader> cr(crb.newCharReader());

    std::string err;
    bool  ret = cr->parse(body.c_str(),body.c_str() + body.size(),Value,&err);
    if(ret == false)
    {
        std::cout << "UnSerialize falied!\n";
        return false;
    }
    return true;
}